<?php

namespace common\modules\openWeixin;

use common\helpers\loggingHelper;
use common\models\DdUser;
use Yii;

/**
 * openWeixin module definition class
 */
class module extends \yii\base\Module
{
    /**
     * {@inheritdoc}
     */
    public $controllerNamespace = 'common\modules\openWeixin\controllers\api';

    /**
     * {@inheritdoc}
     */
    public function init(): void
    {
        parent::init();
        /* 加载语言包 */
        if (!isset(Yii::$app->i18n->translations['wechat'])) {
            Yii::$app->i18n->translations['wechat'] = [
                'class' => 'yii\i18n\PhpMessageSource',
                'sourceLanguage' => 'en',
                'basePath' => '@api/modules/wechat/messages',
            ];
        }
        $appId = Yii::$app->id;
        switch ($appId) {
            case 'app-admin':
                $this->controllerNamespace = 'common\modules\openWeixin\controllers\admin';
                $this->on(self::EVENT_BEFORE_ACTION, function ($event) {
                    loggingHelper::writeLog('officialaccount', 'moduleInit', '监听用户登录事件', [
                        'event' => $event->name
                    ]);
                    // 监听用户登录事件
                    Yii::$app->user->on(Yii\web\User::EVENT_AFTER_LOGIN, function ($event) {
                        $userId = Yii::$app->user->getId();
                        // 使用 $userId 进行初始化处理数据...
                        loggingHelper::writeLog('officialaccount', 'moduleInit', '用户初始事件', [
                            'userId' => $userId,
                            'event' => $event->name
                        ]);
                        $this->initGlobalConf($userId);
                    });
                });
                $config = $this->initConf();
                // 将新的配置设置到应用程序
                // 很多都是写 Yii::configure($this, $config)，但是并不适用子模块，必须写 Yii::$App
                Yii::configure(Yii::$app, $config);
                break;
            case 'app-api':
                $this->controllerNamespace = 'common\modules\openWeixin\controllers\api';
                $config = $this->initConf();
                // 将新的配置设置到应用程序
                // 很多都是写 Yii::configure($this, $config)，但是并不适用子模块，必须写 Yii::$App
                Yii::configure(Yii::$app, $config);
                break;
        }
    }


    public function initGlobalConf($user_id): void
    {
        $bloc_id = DdUser::find()->where(['id' => $user_id])->select('bloc_id')->scalar();
        $params = Yii::$app->params;
        $conf = $params['conf'];
        loggingHelper::writeLog('AccessControl', 'initGlobalConf', '权限校验通过处理初始配置数据', [
            'user_id' => $user_id,
            'bloc_id' => $bloc_id,
            'conf' => $conf
        ]);
        Yii::$app->service->commonGlobalsService->getConf($bloc_id);
        loggingHelper::writeLog('AccessControl', 'initGlobalConf', '权限校验通过处理初始配置处理后数据', [
            'user_id' => $user_id,
            'bloc_id' => (int)$bloc_id,
            'conf' => $conf
        ]);
    }

    private function initConf(): array
    {
        $config = require __DIR__ . '/config/config.php';
        // 获取应用程序的组件
        $components = Yii::$app->getComponents();

        // 遍历子模块独立配置的组件部分，并继承应用程序的组件配置
        foreach ($config['components'] as $k => $component) {
            if (isset($component['class']) && !isset($components[$k])) {
                continue;
            }
            $config['components'][$k] = array_merge($components[$k], $component);
        }

        $configPath = Yii::getAlias('@common/config/wechat.php');

        $wechat = [];

        if (file_exists($configPath)) {
            $wechat = require($configPath);
            // 微信开放平台配置
            $config['params']['wechatOpenPlatformConfig'] = array_merge($config['params']['wechatOpenPlatformConfig'],[
                'app_id' => $wechat['app_id'],
                'secret' => $wechat['secret'],
                'token' => $wechat['token'],
                'aes_key' => $wechat['aes_key'],
            ]);
        }



        $params = Yii::$app->params;

        foreach ($params as $key => $value) {
            if (!isset($config['params'][$key])) {
                $config['params'][$key] = $value;
            }
        }
        return $config;
    }



    public function beforeAction($action)
    {
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

}
